<template>
	<view class="aiChatBox">
		<scroll-view 
			scroll-y
			:scroll-top="scrollTop"
		class="chat-message-list">
			<view v-for="(chatMsg, index) in chatList">
				<chat-message messageMaxWidth="70%" :content="chatMsg.content"
					:align="chatMsg.role && chatMsg.role == 'user' ? 'right' : 'left'"
					:headerImg="chatMsg.role && chatMsg.role == 'user' ? 'https://biz-scrm.oss-cn-shanghai.aliyuncs.com/customerHeader.png' : 'https://biz-scrm.oss-cn-shanghai.aliyuncs.com/images/ai.png'">
					></chat-message>
				<view v-if="chatMsg.content && chatMsg.content.indexOf('转人工') > -1" class="chat-message-button flex">
					<view>
						<u-button type="primary" plain size="small" shape="circle">转人工</u-button>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="chat-bottom">
			<view class="chat-input">
				<u-input v-model="inputMessage" placeholder="请输入您的问题...">
					<u-button slot="suffix" type="primary" size="small" shape="circle"
						@click="sendMessage">发送</u-button>
				</u-input>
			</view>
		</view>
		<u-toast ref="toast"></u-toast>
	</view>

</template>

<script>
	import chatMessage from "@/pages/card/chatMessage";
	import api from "@/api/api";
	import {ChunkRes} from "chunk-res"
	export default {
		props: {
			wechatUserId: Number
		},
		data() {
			return {
				inputMessage: "",
				chatAssistant: null,
				apiKey: null,
				sessionId: "162c5934201e11f0b58e661a8ca18e29",
				chatList: [],
				chunkRes: new ChunkRes(),
				lastData: new Uint8Array(),
				scrollTop: 9999
			}
		},
		components: {
			chatMessage
		},
		mounted() {
			console.log("in onLoad")
			this.loadChatAssistantInfo();
		},
		methods: {
			loadChatAssistantInfo() {
				this.depot.get(api.aiCard("ragflowChatAssistant/findChatAssistantByType?type=AI_CARD&wechatUserId=" + this.wechatUserId))
				.then(res => {
					this.chatAssistant = res && res.data && res.data.data ? res.data.data : null;
					this.apiKey = this.chatAssistant && this.chatAssistant.ragflowUser && this.chatAssistant.ragflowUser.apiKey ? this.chatAssistant.ragflowUser.apiKey : null;
					if (this.apiKey) {
						uni.setStorageSync('ragflowApiKey', this.apiKey)
					}
					let opener = this.chatAssistant && this.chatAssistant.opener ? this.chatAssistant.opener : null;
					if (opener) {
						this.chatList.push({
							"role": "assistant",
							"content": opener
						})
					}
				})
			},
			loadWechatUserInfo() {
				this.depot.get(api.aiCard("wechatUser/findWechatUserByOpenId?openId=" + uni.getStorageSync("openId"))).
				then(res => {
					let expireData = res && res.data && res.data.data && res.data.data.chatAssistantSubscriptionEndTime ? res.data.data.chatAssistantSubscriptionEndTime : null;
					this.subscription.expireDate = expireData && expireData.length > 10 ? expireData.substring(0, 10) : expireData;
				})
			},
			async sendMessage() {
				if (!this.inputMessage) {
					this.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "请输入您的问题"
					});
					return;
				}
				
				this.chatList.push({
					"role": "user",
					"content": this.inputMessage
				})
				
				let inputMessage = this.inputMessage;
				this.inputMessage = "";
				if (this.wechatUserId != 1) {
					// 非霄客客服， 要校验是否订阅服务
					if (await this.isSubscriptionExpired()) {
						return;
					}
				}
				
				
				if (this.apiKey && this.chatAssistant && this.chatAssistant.chatAssistantId) {
					let chatId = this.chatAssistant.chatAssistantId;
					
					let header = {
						"Content-Type": "application/json",
						Authorization: "Bearer " + this.apiKey
					}
					
					let response = await this.depot.post(api.ragflow("chats/" + chatId + "/sessions"), {
					}, header)
					this.sessionId = response && response.data && response.data.data && response.data.data.id ? response.data.data.id : null;
					
					let apiUrl = "chats/" + chatId + "/completions";
					let chatData = {
						question: inputMessage,
						stream: true
					}
					if (this.sessionId) {
						chatData.session_id = this.sessionId;
					}
					response = await this.depot.streamRequest(
					api.ragflow(apiUrl),
					"POST",
					chatData,
					header,
					this.receiveChatMessage)
				} else {
					if (this.chatAssistant.emptyResponse) {
						this.chatList.push({
							"role": "assistant",
							"content": this.chatAssistant.emptyResponse
						})
					}
				}
				this.newMessageIndex = this.chatList.length;
				setTimeout(() => {
					this.scrollTop = this.scrollTop + 9999999999;
					this.$forceUpdate()
				}, 100)
			},
			receiveChatMessage(chunk) {
				console.log("chunk", chunk)
				let message = null;
				let messageId = null;
				if (chunk) {
					while (chunk.indexOf("}\n\n") > -1) {
						chunk = chunk.replace("}\n\n", "}")
					}
					// 删除第一个data:
					chunk = chunk.replace("data:", "")
					let chunkList = chunk.split("data:");
					if (chunkList && chunkList.length > 0) {
						for(let i= 0; i < chunkList.length; i++) {
							chunk = chunkList[i];
							if (chunk) {
								try {
									let messageData = JSON.parse(chunk);
									messageData = messageData.data ? messageData.data : null;
									message = messageData.answer ? messageData.answer : null;
									messageId = messageData.id ? messageData.id : null;
 								} catch(e) {
									console.log("json转换出错", e);
								}
								// let messageData = chunk.replace("data:{", "{");
								// // 用正则表达式而不用JSON.prase， 防止乱码
								// message = this.getBetweenStr(chunk, '"answer": "', '", "');
								// messageId = this.getBetweenStr(chunk, '"id": "', '", "');
							}
						}
					}
					// if (this.newMessageIndex == this.chatList.length) {
					// 	this.chatList.push(message);
					// }
					// console.log("in receiveChatMessage", chunk)	
				}
				message = message ? message.replace(/##(\d+)\$\$/g, "") : null;
				let chatIndex = null;
				for (let i= 0; i < this.chatList.length; i++) {
					let chatInfo = this.chatList[i];
					if (chatInfo.messageId && chatInfo.messageId == messageId) {
						chatIndex = i;
					}
				}
				if (message) {
					if (chatIndex == null) {
						this.chatList.push({
							"role": "assistant",
							"content": message,
							"messageId": messageId
						})
					} else {
						this.chatList[chatIndex].content = message;
					}
				}
				
				setTimeout(() => {
					this.scrollTop = this.scrollTop + 9999999999;
					this.$forceUpdate()
				}, 500)
			},
			getBetweenStr(str, start, end) {
			  let res = str.match(new RegExp(`${start}(.*?)${end}`));
			  return res ? res[1] : null;
			},
			async isSubscriptionExpired() {
				let res = await this.depot.get(api.aiCard("wechatUser/findWechatUserByOpenId?openId=" + uni.getStorageSync("openId")));
				let chatAssistantSubscriptionEndTime = res && res.data && res.data.data && res.data.data.chatAssistantSubscriptionEndTime ? res.data.data.chatAssistantSubscriptionEndTime : null;
				if (chatAssistantSubscriptionEndTime) {
						  chatAssistantSubscriptionEndTime = new Date(chatAssistantSubscriptionEndTime);
						  if (new Date().getTime() < chatAssistantSubscriptionEndTime.getTime()) {
							  return false;
						  } else {
							  return true;
						  }
				} else {
					return true;
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.aiChatBox {
		position: relative;
		height:100%;
	}

	.chat-bottom {
		position: absolute;
		bottom: calc(20rpx + env(safe-area-inset-bottom));
		width: 100vw;
	}

	.chat-input {
		display: flex;
		padding: 20rpx;
		border-top: 1rpx solid #f5f5f5;

		.u-input {
			flex: 1;
			margin-right: 20rpx;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			padding: 0 20rpx;
		}
	}
	
	.chat-message-list {
		// overflow-y: auto;
		height: calc(100% - 166rpx);
		width: calc(100vw - 20rpx);
		padding-left: 10rpx;
		padding-right: 10rpx;
	}
	
	.chat-message-button {
		margin-left: 50rpx;
	}
</style>